const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require("jsonwebtoken")
const config = require("../config.js")
const svgCaptcha = require("svg-captcha")
const request = require('request');

const { v4 } = require('uuid') // npm install -S uuid
const { setString } = require("../utils/save.js")
const client = require("../utils/redis");

/**
 * @typedef loginJSON
 * @property {string} account.required  - 请输入用户名 - eg: 
 * @property {string} password.required - 请输入密码 - eg: 
 * @property {string} code.required  - 请输入验证码 - eg: 
 * @property {string} uuid.required - 请输入uuid - eg: 
 */
/**
 * 登录
 * @route post /user/login
 * @summary 登录 
 * @group 登录注册模块   
 * @param {loginJSON.model} body.body.required - account&password&code&uuid
 * @returns {object} 200 - {code:200,msg:'ok',data:null}
 * @returns {Error}  default - {code:500,msg:'error',data:null}
 */
exports.login = async (req, res) => {

    let code = await client.get(req.body.uuid)
    if (req.body.code.toLowerCase() !== code) {
        return res.cc('验证码错误')
    }

    const sql = 'select * from users where account = ?';
    db.query(sql, req.body.account, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // 执行 SQL 语句成功，但是查询到数据条数不等于 1
        if (results.length !== 1) return res.cc('登录失败！');

        const isTrue = bcrypt.compareSync(req.body.password, results[0].password);
        if (!isTrue) {
            return res.cc('登录失败！')
        }
        if (results[0].status) {
            return res.cc('账户冻结')
        }
        const user = { ...results[0], password: "", imageUrl: "", create_time: "", update_time: "" }
        const tokenStr = jwt.sign(user, config.jwtSecretKey, {
            expiresIn: '3h'
        })

        res.send({
            status: 0,
            message: '登录成功！',
            //为了方便客户端使用 Token，在服务器端直接拼接上 Bearer 的前缀
            token: 'Bearer ' + tokenStr,
            data: { ...results[0], password: "" }
        })
    })
}

exports.register = async (req, res) => {
    let phone = req.body.phone;
    let code = await client.get(phone)
    if (req.body.code !== code) {
        return res.cc('验证码错误')
    }

    const sql = 'select * from users where account = ?';
    db.query(sql, req.body.account, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        if (results.length > 0) {
            return res.cc('用户名被占用，请更换其他用户名！');
        }
        let newPassword = bcrypt.hashSync(req.body.password, 10);
        const insertSql = "insert into users set ?";
        const identity = '用户';
        const create_time = new Date().toLocaleString();
        db.query(insertSql, {
            account: req.body.account,
            password: newPassword,
            phone,
            identity,
            create_time
        }, (err, results) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            // SQL 语句执行成功，但影响行数不为 1
            if (results.affectedRows !== 1) {
                return res.send({ status: 1, message: '注册用户失败，请稍后再试！' })
            }
            // 注册成功
            res.send({ status: 0, message: '注册成功！' })
        })
    })

}

exports.verify = (req, res) => {
    const sql = "select * from users where account = ? and email = ?";
    // 执行 SQL 语句
    db.query(sql, [req.body.account, req.body.email], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err)
        // 执行 SQL 语句成功，但是影响行数不等于 1
        if (results.length !== 1) return res.cc('验证失败！')
        res.send({
            // 状态
            status: 0,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            message: '验证成功',
            id: results[0].id
        })
    })
}

exports.resetPassword = (req, res) => {
    const sql = "update users set password = ? where id =?";
    const password = bcrypt.hashSync(req.body.password, 10);
    // 执行 SQL 语句
    db.query(sql, [password, req.body.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err)
        // 执行 SQL 语句成功，但是影响行数不等于 1
        if (results.affectedRows !== 1) return res.cc('重置失败！')
        res.cc('重置成功', 0)
    })
}

/**
 * 获取验证码
 * @route get /user/getCaptcha  
 * @summary 获取验证码 
 * @group 登录注册模块
 * @returns {object} 200 - {code:200,msg:'ok',data:null}
 * @returns {Error}  default - {code:500,msg:'error',data:null}
 */
// 获取验证码
exports.getCaptcha = (req, res) => {
    res.header('Access-Control-Allow-Origin', "*");
    // const cap = captcha.create({
    //     size: 4,
    //     ignoreChars: '0o1il',
    //     noise: 1,
    //     color: true,
    //     background: '#cc9966',
    //     width:   73, // 图片长度
    //     height: 32,  // 图片高度
    // });
    // // req.session.captcha = cap.text; // session 存储

    // // let uuid = v4();
    // // setString(uuid, cap.text.toLowerCase(), 300)
    // // client.set(uuid, cap.text.toLowerCase())
    // req.session.captcha = cap.text.toLowerCase(); // session 存储验证码数值
    // console.log(req.session.captcha);


    //验证码配置api
    let options = {
        //线条数
        noise: Math.floor(Math.random() * 5),
        color: true,
        fontSize: 55,
        width: 90,
        height: 38,
    }
    let captcha = svgCaptcha.createMathExpr(options)
    let uuid = v4()
    setString(uuid, captcha.text.toLowerCase(), 300)
    res.type('svg'); // 响应的类型
    res.send({
        img: captcha.data,
        uuid: uuid
    });
}
/**
 * @typedef sendCodeJSON
 * @property {string} phone.required  - 请输入手机号 - eg: 
 */
/**
 * 给手机上发送验证码
 * @route post /user/sendCode  
 * @summary 给手机上发送验证码 
 * @group 登录注册模块
 * @param {sendCodeJSON.model} body.body.required - account&password&code&uuid
 * @returns {object} 200 - {code:200,msg:'ok',data:null}
 * @returns {Error}  default - {code:500,msg:'error',data:null}
 */
// 给手机上发送验证码
exports.sendCode = (req, res) => {
    res.header('Access-Control-Allow-Origin', "*");
    let phone = req.body.phone;
    let randomNum = parseInt(Math.random() * (9999 - 1000 + 1) + 1000);
    console.log(randomNum, phone, req.body); // 输出随机的四位数
    res.cc('发送成功', 0)
    setString(phone, randomNum, 300)
    let url = encodeURI(`http://106.ihuyi.com/webservice/sms.php?method=Submit&account=C25788203&password=ed9c2dc65d698de0762a3270c7a151b6&mobile=${phone}&content=您的验证码是：${randomNum}。请不要把验证码泄露给其他人。`);
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // console.log(response, body) // 请求成功的处理逻辑
        }
    });
}

